﻿using System;
using System.Data;
using Business;
using Common;
using Common.Constant;
using Entity;

public partial class Detail : System.Web.UI.Page
{
    private DataSet _dataSet;
    private PostBus _postBus;
    private CommentBus _commentBus;
    private Comment _comment;
    protected void Page_Load(object sender, EventArgs e)
    {
        ButtonSubmitComment.Attributes.Add("onclick", "return validate()");
        var id = Request.QueryString["id"];
        if(Session["User"] != null)
        {
            LabelLoginName.Text = Session["User"].ToString();
            PanelComementLogin.Visible = true;
            pnCommentNotLogin.Visible = false;
        }
        else
        {
            pnCommentNotLogin.Visible = true;
            PanelComementLogin.Visible = false;
        }
        if (Request.QueryString["id"] != null && Request.QueryString["id"] != "")
        {
            try
            {
                _postBus = new PostBus();
                _dataSet = _postBus.GetPostById(int.Parse(id));
                rptPostDetail.DataSource = _dataSet;
                rptPostDetail.DataBind();

                LoadComment(int.Parse(id));

                _postBus.UpdatePostViewCount(int.Parse(id));
            }
            catch (Exception exception)
            {
                Response.Write(exception.Message);
            }
            
        }
        
    }

    protected void LogoutClick(object sender,EventArgs e)
    {
        Session.Abandon();
        Response.Redirect(Request.RawUrl);
    }

    protected void LoadComment(int postId)
    {
        _commentBus = new CommentBus();
        _dataSet = _commentBus.GetCommentByPostId(postId);
        RepeaterListComment.DataSource = _dataSet;
        RepeaterListComment.DataBind();
    }

    protected void ButtonSubmitCommentClick(object sender, EventArgs e)
    {
        try
            {
                _comment = new Comment();
                _commentBus = new CommentBus();

                _comment.CommentContent = TextBoxComment.Text;
                _comment.UserName = (Session["User"] != null) ? Session["User"].ToString() : TextBoxName.Text;
                _comment.Email = (Session["User"] != null) ? "" : TextBoxEmail.Text;
                _comment.CommentDate = DateTime.Now;
                _comment.PostId = int.Parse(Request.QueryString["id"]);
                _comment.IsPublish = DBSchemas.DefaultCommentPublish;

                _commentBus.AddComment(_comment);
                Response.Redirect(Request.RawUrl);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
